import urllib

import pymongo
import redis

from Configs.setting import *


class MyException(Exception):  # 继承异常类
    def __init__(self, name, reason):
        self.name = name
        self.reason = reason


r = redis.Redis(Redis_HOST, password=Redis_PASSWORD, decode_responses=True, db=Redis_DB)  # ,health_check_interval=30


class DB_MongoDB:

    def __init__(self, host=Mongo_HOST, port=Mongo_PORT, db=Mongo_DB, username=Mongo_USERNAME,
                 password=Mongo_PASSWORD):
        username = urllib.parse.quote_plus(username)
        password = urllib.parse.quote_plus(password)
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.db = db
        self.coon()

    def coon(self):
        # con_url = f'mongodb://{self.username}:{self.password}@{self.host}:{self.port}/?authSource={self.db}'
        con_url = f'mongodb://root:%qq123456..@192.168.44.131:27017'
        # con_url = url
        client = pymongo.MongoClient(con_url)
        self.db = client[self.db]
        # logger.debug("连接成功")

    def db_instance(self, table_name):
        return self.db[table_name]

    def aggregate(self, table_name, find_list):
        col_ = self.db[table_name]
        res = col_.aggregate(find_list)
        return [i for i in res]

    def save(self, table_name, data_list):
        '''
        ordered 参数表示遇到错误是否继续
        :param table_name:
        :param data_list:
        :return:
        '''
        repeat_list = []
        success_list = []
        faild_list = []
        try:
            col_ = self.db[table_name]
            for d in data_list:
                if not d:
                    continue
                try:
                    col_.insert_one(d)
                    success_list.append(d)
                except pymongo.errors.DuplicateKeyError:
                    repeat_list.append(d)
                    # logger.error(f"插入数据重复")
                except Exception as e:
                    faild_list.append(d)
                    logger.error(f"插入数据错误:{e}！")
            return repeat_list, success_list, faild_list
        except:
            logger.exception("发生未知错误！")
            return [], [], []

    def save_to_id(self, table_name, data):
        '''
        ordered 参数表示遇到错误是否继续
        :param table_name:
        :param data_list:
        :return:
        '''
        try:
            col_ = self.db[table_name]

            try:
                result = col_.insert_one(data)
                _id = result.inserted_id
            except pymongo.errors.DuplicateKeyError:
                logger.error('数据已存在')
                return False
            return _id
        except:
            logger.exception("发生未知错误！")
            return False

    # 查mongo数据库，并返回列表 lst
    def find(self, table_name, find, field=None, limit=None, count=None, sort=None):
        try:
            col_ = self.db[table_name]
            if sort:
                res = col_.find(find, field).sort(sort)
            else:
                if field and limit and count:
                    res = col_.find(find, field).limit(limit).count()
                    return res
                elif field and limit:
                    res = col_.find(find, field).limit(limit)
                elif limit and count:
                    res = col_.find(find).limit(limit).count()
                    return res
                elif field and count:
                    res = col_.find(find, field).count()
                    return res
                elif field:
                    res = col_.find(find, field)
                elif limit:
                    res = col_.find(find).limit(limit)
                elif count:
                    res = col_.find(find).count()
                    return res
                else:
                    res = col_.find(find)
            return [i for i in res]
        except Exception as e:
            logger.error(f'mongo查询失败，失败原因为：{e},失败查询参数为：{find}')
            return []

    def update(self, table_name, query_info, update_info, multi=False, choosable=None):
        col_ = self.db[table_name]
        if choosable:
            res = col_.update(query_info, update_info, choosable, multi=multi)
        else:
            res = col_.update(query_info, update_info, multi=multi)
        return res

    def remove(self, table_name, query_info):
        col_ = self.db[table_name]
        col_.delete_one(query_info)

    def remove_all(self, table_name, query_info):
        col_ = self.db[table_name]
        num = col_.delete_many(query_info)
        return num

    def distinct(self, table_name, field_name,query_info):
        col_ = self.db[table_name]
        res = col_.distinct(field_name,query_info)
        return res


DB_MongoDB2 = DB_MongoDB()
if __name__ == '__main__':
    result = DB_MongoDB().find('start_table', {'rule': 'Rsc'})
    logger.debug(result)
